package whf.framework.util;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author wanghaifeng
 *
 * @param <T>
 */
public class NewInstance<T> {
	
	/**
	 * such as : /temp/dynacode_classes/
	 */
	private String classesDir;
	
	public NewInstance(String classesDir){
		this.classesDir = classesDir;
	}
	
	public T loadInstance(Class interfaceClass, String implementsClassName) throws Exception {
		File classesDir = new File(this.classesDir);

		ClassLoader parentLoader = interfaceClass.getClassLoader();
		URLClassLoader classCloader = new URLClassLoader(new URL[] { classesDir.toURL() }, parentLoader);
		Class cls1 = classCloader.loadClass(implementsClassName);
		T result = (T) cls1.newInstance();

		return result;
	}

	public T reloadInstance(Class interfaceClass, String implementsClassName) throws Exception {
		File classesDir = new File(this.classesDir);
		ClassLoader parentLoader = interfaceClass.getClassLoader();
		URLClassLoader classLoader = new URLClassLoader(new URL[] { classesDir.toURL() }, parentLoader);
		Class cls2 = classLoader.loadClass(implementsClassName);
		T result = (T) cls2.newInstance();
		return result;

	}
//	class DynaCodeInvocationHandler implements InvocationHandler {
//
//	    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//	        
//	        // Get an instance of the up-to-date dynamic class
//	        Object dynacode = getUpToDateInstance();
//	        
//	        // Forward the invocation
//	        return method.invoke(dynacode, args);
//	    }
//	}
}
